package top.yehot.cmmu.shiro.session;

import java.util.Objects;

import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.session.Session;
import org.apache.shiro.session.mgt.SessionContext;
import org.apache.shiro.session.mgt.SessionFactory;
import org.apache.shiro.web.session.mgt.WebSessionContext;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import cn.hutool.crypto.digest.MD5;
import eu.bitwalker.useragentutils.UserAgent;
import top.yehot.cmmu.core.utils.JIpUtil;

/**
 * <p>自定义 SessionFactory 类，参考【若依】</p>
 * <p>参考类URL：https://gitee.com/y_project/RuoYi/blob/master/ruoyi-framework/src/main/java/com/ruoyi/framework/shiro/session/OnlineSessionFactory.java</p>
 * 
 * @author lquan
 * @date 2022-9-9 21:08:04
 */
public class CustomSessionFactory implements SessionFactory {

	@Override
	public Session createSession(SessionContext initData) {
		CustomSession session = new CustomSession();
		if (Objects.nonNull(initData) && initData instanceof WebSessionContext) {
			WebSessionContext sessionContext = (WebSessionContext) initData;
			HttpServletRequest request = (HttpServletRequest) sessionContext.getServletRequest();
			
			if (Objects.nonNull(request)) {
				ServletRequestAttributes springRequest = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
				// 获取User-Agent
				String userAgentStr = springRequest.getRequest().getHeader("User-Agent");
				// 获取IP
				String ipAddr = JIpUtil.getIpAddr(request);
				// 特征信息
				String features = MD5.create().digestHex(ipAddr + userAgentStr);
				// 解析User-Agent工具类
				UserAgent userAgent = UserAgent.parseUserAgentString(userAgentStr);
				
				// 客户端IP
				session.setHost(ipAddr);
				// 客户端操作系统
				session.setOs(userAgent.getOperatingSystem().getName());
				// 客户端浏览器
				session.setBrowser(userAgent.getBrowser().getName());
				// 客户端特征码
				session.setFeatures(features);
			}
		}
		return session;
	}

}
